﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using ThreeByte.ActiveDeck.Service;
using ThreeByte.ActiveDeck.Data.UserResponse;
using System.IO;
using ThreeByte.Media;
using System.Windows.Threading;
using System.Windows;
using ThreeByte.ActiveDeck.Config;
using Excel = Microsoft.Office.Interop.Excel;
using log4net;

namespace ThreeByte.ActiveDeck.AddIn.Content.UserResponse
{
    public class ChartUpdater : UserResponseFeedbackUpdater
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ChartUpdater));

        private PowerPoint.Chart MyChart;

        private PowerPoint.ChartData MyChartData;
        private Excel.Workbook MyWorkbook;
        private Excel.Worksheet MyWorksheet;

        private MultipleChoiceConfig QuestionConfig;
        private MultipleChoiceUserData UserData;

        private Dispatcher Dispatcher;

        public ChartUpdater(string presentation, PowerPoint.Shape shape, WebServiceClient client, MultipleChoiceConfig questionConfig, Dispatcher dispatcher)
            : base(presentation, shape, client) {
        
            MyChart = MyShape.Chart;
            MyChartData = MyChart.ChartData;
            MyChart.ChartData.Activate();
            MyWorkbook = (Excel.Workbook)MyChart.ChartData.Workbook;
            MyWorkbook.Application.WindowState = Excel.XlWindowState.xlMinimized;
            MyWorksheet = MyWorkbook.Worksheets[1];

            QuestionConfig = questionConfig;
            UserData = questionConfig.InitUserData();

            Dispatcher = dispatcher;
        }

        protected override bool UpdateUserData(System.Xml.Linq.XElement userData) {
            AggregateUserData newUserData = AggregateUserData.ParseXml(userData);
            return UserData.UpdateUserData(newUserData);
        }

        protected override void UpdateGraphic() {

            Dispatcher.Invoke((Action)delegate {
                UpdateGraphicOnDispatcher();
            }, null); 
            
        }

        private void UpdateGraphicOnDispatcher() {
            log.Debug("Updating chart graphic");
            foreach(MultipleChoiceAnswerData m in UserData.Answers) {
                string cell = string.Format("b{0}", m.Value + 1);
                log.DebugFormat("Updating cell {0} with value {1} from Thread {2}", cell, m.UserResponses, System.Threading.Thread.CurrentThread.ManagedThreadId);
                try {
                    MyWorksheet.Range[cell].Value = m.UserResponses;
                } catch(Exception ex) {
                    log.Error("The range could not be updated", ex);
                }
            }

        }

        public override void Dispose() {
            base.Dispose();
            log.Debug("Closing the workbook");
            MyWorkbook.Close();
        }
    }
}
